const { validationResult } = require('express-validator');
const Comment = require('../models/Comment');
const Video = require('../models/Video');
const User = require('../models/User');
const Message = require('../models/Message');
const sequelize = require('../config/database');

class CommentController {
  // 获取视频评论列表
  static async getVideoComments(req, res) {
    try {
      const { page = 1, limit = 20, sortBy = 'created_at', order = 'desc' } = req.query;
      
      // 检查视频是否存在
      const videoExists = await Video.findByPk(req.params.video_id || req.params.videoId);
      if (!videoExists) {
        return res.status(404).json({ success: false, message: '视频不存在' });
      }
      
      const videoId = req.params.video_id || req.params.videoId;
      // 使用原始查询来避免Sequelize的字段名映射问题
      const sqlQuery = `
        SELECT c.*, 
               u.id as user_id, u.username, u.avatar,
               COUNT(DISTINCT r.id) as reply_count
        FROM comments c
        LEFT JOIN users u ON c.user_id = u.id
        LEFT JOIN comments r ON c.id = r.parent_id AND r.status = 1
        WHERE c.video_id = ? AND c.parent_id IS NULL AND c.status = 1
        GROUP BY c.id
        ORDER BY c.${sortBy} ${order}
        LIMIT ? OFFSET ?
      `;
      
      const rows = await sequelize.query(sqlQuery, {
        replacements: [videoId, parseInt(limit), (parseInt(page) - 1) * parseInt(limit)],
        type: sequelize.QueryTypes.SELECT
      });
      
      // 获取总数
      const countQuery = `
        SELECT COUNT(*) as count 
        FROM comments 
        WHERE video_id = ? AND parent_id IS NULL AND status = 1
      `;
      const countResult = await sequelize.query(countQuery, {
        replacements: [videoId],
        type: sequelize.QueryTypes.SELECT
      });
      const count = countResult[0].count;
      
      res.json({
        success: true,
        data: {
          comments: rows,
          pagination: {
            total: count,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(count / limit)
          }
        }
      });
    } catch (error) {
      console.error('获取视频评论失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 创建评论
  static async createComment(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({ success: false, message: '验证失败', errors: errors.array() });
      }
      
      const { content, parentId } = req.body;
      const userId = req.user.id;
      const videoId = req.params.videoId;
      
      // 检查视频是否存在
      const videoExists = await Video.findByPk(videoId);
      if (!videoExists) {
        return res.status(404).json({ success: false, message: '视频不存在' });
      }
      
      // 如果是回复评论，检查父评论是否存在
      let parentComment = null;
      if (parentId) {
        parentComment = await Comment.findByPk(parentId);
        if (!parentComment) {
          return res.status(404).json({ success: false, message: '父评论不存在' });
        }
        // 确保父评论属于同一个视频
        if (parentComment.video_id !== videoId) {
          return res.status(400).json({ success: false, message: '父评论不属于该视频' });
        }
      }
      
      const comment = await Comment.create({
        video_id: videoId,
        user_id: userId,
        parent_id: parentId,
        content,
        like_count: 0
      });
      
      // 获取完整的评论信息（包含用户信息）
      const fullComment = await Comment.findByPk(comment.id, {
        include: [{ model: User, as: 'user', attributes: ['id', 'username', 'avatar'] }]
      });
      
      // 创建评论消息通知
      try {
        if (parentId && parentComment) {
          // 如果是回复评论，通知被回复的评论作者
          if (userId !== parentComment.user_id) {
            await Message.createCommentMessage(userId, parentComment.user_id, comment.id, 'comment', content);
          }
        } else {
          // 如果是直接评论视频，通知视频作者
          if (userId !== videoExists.user_id) {
            await Message.createCommentMessage(userId, videoExists.user_id, comment.id, 'video', content);
          }
        }
      } catch (messageError) {
        console.error('创建评论消息失败:', messageError);
        // 消息创建失败不影响评论操作
      }
      
      res.status(201).json({ success: true, message: '评论成功', data: fullComment });
    } catch (error) {
      console.error('创建评论失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 删除评论
  static async deleteComment(req, res) {
    try {
      const comment = await Comment.findByPk(req.params.id);
      
      if (!comment) {
        return res.status(404).json({ success: false, message: '评论不存在' });
      }
      
      // 检查权限：只有评论作者或管理员可以删除评论
      if (comment.user_id !== req.user.id && req.user.role !== 'admin') {
        return res.status(403).json({ success: false, message: '没有权限删除此评论' });
      }
      
      // 递归删除所有回复
      await CommentController.deleteCommentRecursive(comment.id);
      
      res.json({ success: true, message: '评论删除成功' });
    } catch (error) {
      console.error('删除评论失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }
  
  // 更新评论
  static async updateComment(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({ success: false, message: '验证失败', errors: errors.array() });
      }
      
      const { content } = req.body;
      const comment = await Comment.findByPk(req.params.id);
      
      if (!comment) {
        return res.status(404).json({ success: false, message: '评论不存在' });
      }
      
      // 检查权限：只有评论作者可以更新评论
      if (comment.user_id !== req.user.id) {
        return res.status(403).json({ success: false, message: '没有权限更新此评论' });
      }
      
      // 更新评论内容
      comment.content = content;
      await comment.save();
      
      // 获取更新后的完整评论信息
      const updatedComment = await Comment.findByPk(comment.id, {
        include: [{ model: User, as: 'user', attributes: ['id', 'username', 'avatar'] }]
      });
      
      res.json({ success: true, message: '评论更新成功', data: updatedComment });
    } catch (error) {
      console.error('更新评论失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 递归删除评论及其回复
  static async deleteCommentRecursive(commentId) {
    const replies = await Comment.findAll({ where: { parent_id: commentId } });
    
    for (const reply of replies) {
      await CommentController.deleteCommentRecursive(reply.id);
    }
    
    await Comment.destroy({ where: { id: commentId } });
  }

  // 评论点赞/取消点赞
  static async toggleCommentLike(req, res) {
    try {
      const comment = await Comment.findByPk(req.params.id);
      
      if (!comment) {
        return res.status(404).json({ success: false, message: '评论不存在' });
      }
      
      // 简单实现：直接增加/减少点赞数（实际项目中应该有用户点赞记录）
      // 这里为了简化，我们假设前端会管理点赞状态
      // 初始化liked属性
      comment.liked = comment.liked || false;
      const result = await comment.toggleLike();
      
      res.json({ 
        success: true, 
        message: result.liked ? '点赞成功' : '取消点赞成功',
        data: { likeCount: result.likeCount, liked: result.liked }
      });
    } catch (error) {
      console.error('操作评论点赞失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 获取用户的评论历史
  static async getUserComments(req, res) {
    try {
      const { page = 1, limit = 20 } = req.query;
      
      const { count, rows } = await Comment.findAndCountAll({
        where: { user_id: req.user.id },
        limit: parseInt(limit),
        offset: (parseInt(page) - 1) * parseInt(limit),
        order: [['created_at', 'desc']],
        include: [
          { model: Video, attributes: ['id', 'title', 'cover_url'] }
        ]
      });
      
      res.json({
        success: true,
        data: {
          comments: rows,
          pagination: {
            total: count,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(count / limit)
          }
        }
      });
    } catch (error) {
      console.error('获取用户评论历史失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }
}

module.exports = CommentController;